package com.letv.whatslive.mongo.dao;


import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.CacheConstants;
import com.letv.whatslive.common.utils.Constants;
import com.letv.whatslive.common.utils.DateUtils;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.User;
import com.letv.whatslive.model.constant.UserConstants;
import com.letv.whatslive.model.convert.UserConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.letv.whatslive.redis.JedisDAO;
import com.mongodb.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 用户collection操作DAO
 * Created by gaoshan on 15-07-07.
 */
@Repository
public class UserDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(UserDAO.class);

    protected String collectionName = "user";

    @Autowired
    protected JedisDAO jedisDAO;

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public int saveOrUpdateUser(User user,Integer... saveType) {
        WriteResult result = null;
        if(user!=null && user.getUserId()!=null){
            DBObject query = new BasicDBObject("_id", user.getUserId());
            DBObject dbo = this.dbCollection.findOne(query);
            if (dbo == null) {//insert
                dbo = UserConvert.castUserToDBObject(user);
                if (dbo != null) {

                    String nickName = ObjectUtils.toString(user.getNickName(), "");
                    try {

                        // 删除昵称中的数字后缀
                        String regEx = "(_\\d{3})+$";
                        String newNickName = nickName.replaceAll(regEx, "");
                        if (StringUtils.isNotBlank(newNickName)) {

                            dbo.put("nickName", newNickName);
                        }

                        result = this.dbCollection.save(dbo);
                    } catch (DuplicateKeyException e) {

                        // 如果删除数字后缀后，昵称有重复，则使用原昵称
                        dbo.put("nickName", nickName);
                        result = this.dbCollection.save(dbo);
                    }
                }
            } else {//update
                DBObject update = new BasicDBObject();

                if (user.getSex() != null &&  user.getSex() >= -1) {
                    update.put("sex", user.getSex());
                }
                if(user.getBroadCastNum() != null && user.getBroadCastNum() > 0){
                    update.put("broadCastNum",user.getBroadCastNum());
                }
                if(user.getLikeNum() != null && user.getLikeNum() > 0){
                    update.put("likeNum",user.getLikeNum());
                }
                if (StringUtils.isNotBlank(user.getUserName()) && saveType.length==0) {
                    update.put("userName", user.getUserName());
                }

                if (StringUtils.isNotBlank(user.getPicture()) && saveType.length==0) {
                    update.put("picture", user.getPicture());
                }

                if (StringUtils.isNotBlank(user.getNickName()) && saveType.length==0) {
                    update.put("nickName", user.getNickName());
                }

                if (saveType.length==0) {
                    update.put("introduce", user.getIntroduce());
                }

                update.put("userType", ObjectUtils.toInteger(user.getUserType(), 0));
                update.put("qqBind", ObjectUtils.toInteger(user.getQqBind(), 0));
                update.put("sinaBind", ObjectUtils.toInteger(user.getSinaBind(), 0));
                update.put("weixinBind", ObjectUtils.toInteger(user.getWeixinBind(), 0));
                update.put("qqId", ObjectUtils.toString(user.getQqId(), ""));
                update.put("sinaId", ObjectUtils.toString(user.getSinaId(), ""));
                update.put("weixinId", ObjectUtils.toString(user.getWeixinId(), ""));
                update.put("updateTime", System.currentTimeMillis());
                update.put("lastLoginTime", System.currentTimeMillis());
                update.put("accessToken",user.getAccessToken());
                update.put("devIdList",user.getDevIdList());
                update.put("sso_tk",user.getSsoTk());
                result = this.dbCollection.update(query, new BasicDBObject("$set", update), true, false);
            }
        }else{
            return ObjectUtils.toInteger(this.insert(UserConvert.castUserToDBObject(user)));
        }
        return result.getN();

    }

    /**
     * 查询用户列表
     *
     * @param params 模糊查询的查询条件
     * @param orders 排序的条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<User> getUserListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<User> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        //TODO 临时用于检查错误用户数据
        User errorUser = new User();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                User user = UserConvert.castDBObjectToUser(dbObject);
                errorUser = user;
                setValueToUser(user);
                result.add(user);
            }
        } catch (Exception e) {
            logger.error("uid:<"+errorUser.getUserId()+"> error:<"+e.getMessage()+">",e);
        }
        return result;
    }

    public List<User> getUserListByParamsWithOutSetValue(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<User> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                User user = UserConvert.castDBObjectToUser(dbObject);
                result.add(user);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return result;
    }



    /**
     * 查询用户列表(api)
     *
     * @param params 模糊查询的查询条件
     * @param orders 排序的条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<User> getUserListByParamsApi(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<User> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query).skip((start - 1) * limit).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                User user = UserConvert.castDBObjectToUser(dbObject);
                setValueToUser(user);
                result.add(user);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    public List<User> getAllUserByParams(Map<String, Object> params){
        List<User> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                User user = UserConvert.castDBObjectToUser(dbObject);
                setValueToUser(user);
                result.add(user);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据主键查询一个用户
     * @param uid 用户主键
     * @return 一个User对象
     */
    public User getUserById(Long uid, String... readPreference) {
        BasicDBObject query = new BasicDBObject();
        User user = new User();
        query.put("_id", uid);
        DBObject dbObject = null;

        if (readPreference != null && readPreference.length > 0
                && Constants.MONGO_READPREFERENCE_PRIMARY.equals(readPreference[0])) {

            dbObject = this.dbCollectionOnPrimary.findOne(query);
        } else {

            dbObject = this.dbCollection.findOne(query);
        }

        if (dbObject == null) return null;
        try {
            user = UserConvert.castDBObjectToUser(dbObject);
            setValueToUser(user);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return user;
    }

    public User getAdminUser() {
        BasicDBObject query = new BasicDBObject();
        User user = new User();
        query.put("role", 2);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            user = UserConvert.castDBObjectToUser(dbObject);
            setValueToUser(user);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return user;
    }

    /**
     * 根据用户ID的集合查询一组用户
     * @param idList
     * @return
     */
    public Map<Long ,User> getUsersByIds(List<Long> idList){
        Map<Long ,User> users = new HashMap<Long, User>();
        BasicDBList values = new BasicDBList();
        for (Long id : idList) {
            values.add(id);
        }
        BasicDBObject queryCondition = new BasicDBObject();
        queryCondition.put("_id", new BasicDBObject("$in", values));
        DBCursor cur = this.dbCollection.find(queryCondition);
        while (cur.hasNext()) {
            DBObject dbObject = cur.next();
            User user = UserConvert.castDBObjectToUser(dbObject);
            setValueToUser(user);
            users.put(user.getUserId(), user);
        }
        return users;
    }

    /**
     * 查询用户的数量
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countUserByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 保存用户信息
     * @param user
     * @return
     */
    public User saveUser(User user) {
        try {
            user.setUserId(getAutoIncrementId());
            user.setRole(UserConstants.role_normal);
            user.setUserType(UserConstants.userType_system);
            DBObject dbo = UserConvert.castUserToDBObject(user);
            if(user.getPicture()==null || user.getPicture().length()==0){
                dbo.removeField("picture");
            }
            WriteResult wr = this.dbCollection.insert(dbo);
            return user;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 更新用户基本信息
     * @param user
     */
    public void updateUser(User user) {
        DBObject queryCondition = new BasicDBObject();
        Long userId = user.getUserId();
        queryCondition.put("_id", userId); // 用来确定要修改的文档
        DBObject setValue = UserConvert.castUserToDBObject(user);
        //剔除主键修改
        if (setValue.containsKey("_id")) {
            setValue.removeField("_id");
        }
        if(user.getPicture()==null || user.getPicture().length()==0){
            setValue.removeField("picture");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    /**
     * 更新用户基本信息
     * @param user
     */
    public void updateUserUnsetColumn(User user) {
        DBObject queryCondition = new BasicDBObject();
        Long userId = user.getUserId();
        queryCondition.put("_id", userId); // 用来确定要修改的文档
//        DBObject setValue = UserConvert.castUserToDBObject(user);
        DBObject setValue=new BasicDBObject();
        if(user.getCountryCodeId()==null)
            setValue.put("countryCodeId",1);
        if(StringUtils.isBlank(user.getRealNamePhoneNo()))
            setValue.put("realNamePhoneNo",1);
        //剔除主键修改
//        if (setValue.containsKey("_id")) {
//            setValue.removeField("_id");
//        }
        DBObject values = new BasicDBObject("$unset", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }


    /**
     * 根据用户ID删除用户
     * @param uid
     */
    public void deleteUser(Long uid){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", uid);
        this.dbCollection.remove(query);
    }

    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {

            if (params.get("userId") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("userId")));
            }
            if (params.get("userName") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("userName") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("userName", pattern);
            }
            if (params.get("nickName") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("nickName") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("nickName", pattern);
            }
            if (params.get("nickName_exactly") != null) {
                query.put("nickName", ObjectUtils.toString(params.get("nickName_exactly")));
            }
            if (params.get("userRole") != null) {
                String roleString = ObjectUtils.toString(params.get("userRole"));
                if (roleString.length() > 2) {
                    BasicDBList values = new BasicDBList();
                    String[] roleArray = roleString.split(",");
                    for (String role : roleArray) {
                        values.add(ObjectUtils.toInteger(role));
                    }
                    query.put("role", new BasicDBObject("$in", values));
                } else {
                    query.put("role", ObjectUtils.toInteger(roleString));
                }
            }
            if (params.get("userLevel") != null) {
                query.put("level", ObjectUtils.toInteger(params.get("userLevel")));
            }
            if (params.get("userType") != null) {
                query.put("userType", ObjectUtils.toInteger(params.get("userType")));
            }
            if(params.get("userTypeNotEqual") != null){
                query.put("userType", new BasicDBObject("$ne", ObjectUtils.toLong(params.get("userTypeNotEqual"))));
            }
            if (params.get("broadCastNum") != null) {
                query.put("broadCastNum", new BasicDBObject("$gt", ObjectUtils.toLong(params.get("broadCastNum"))));
            }
            if (params.get("userIdNotEqual") != null) {
                query.put("_id", new BasicDBObject("$ne", ObjectUtils.toLong(params.get("userIdNotEqual"))));
            }
            if(params.get("startTime_start") != null && params.get("startTime_end") != null){
                query.put("createTime", new BasicDBObject("$gt",
                        ObjectUtils.toLong(params.get("startTime_start"))).append("$lte", ObjectUtils.toLong(params.get("startTime_end"))));

            }
            if (params.get("userStatus") != null) {
                query.put("userStatus", ObjectUtils.toInteger(params.get("userStatus")));
            }
            if(params.get("tags.tagId") != null){
                query.put("tags.tagId", ObjectUtils.toLong(params.get("tags.tagId")));
            }
            if (params.get("isRobot") != null){
                query.put("isRobot", new BasicDBObject("$ne", 0));
            }
            if (params.get("isHasRobot") != null){
                query.put("isHasRobot", ObjectUtils.toInteger(params.get("isHasRobot")));
            }
            if (params.get("notIncludeRoleManager") != null){
                query.put("role", new BasicDBObject("$ne",2));
            }
            if (params.get("userIdNotInList") != null) {
                List<Long> userIds = (List<Long>) params.get("userIdNotInList");
                BasicDBList values = new BasicDBList();
                if (userIds != null && userIds.size() > 0) {
                    for (Long userid : userIds) {
                        values.add(ObjectUtils.toLong(userid));
                    }
                    query.put("_id", new BasicDBObject("$nin", values));
                }
            }
            if (params.get("userIdInList") != null) {
                List<Long> userIds = (List<Long>) params.get("userIdInList");
                BasicDBList values = new BasicDBList();
                if (userIds != null && userIds.size() > 0) {
                    for (Long userid : userIds) {
                        values.add(ObjectUtils.toLong(userid));
                    }
                    query.put("_id", new BasicDBObject("$in", values));
                }
            }
            if (params.get("isContracted") != null) {
                query.put("isContracted", ObjectUtils.toInteger(params.get("isContracted")));
            }
            if (params.get("appId") != null) {
                query.put("appId", ObjectUtils.toString(params.get("appId")));
            }
            if (params.get("realNamePhoneNo") != null) {
                query.put("realNamePhoneNo", ObjectUtils.toString(params.get("realNamePhoneNo")));
            }
            if (params.get("countryCodeId") != null) {
                query.put("countryCodeId", ObjectUtils.toLong(params.get("countryCodeId")));
            }
            if (params.get("openid") != null) {
                query.put("openid", ObjectUtils.toString(params.get("openid")));
            }
            if (params.get("openidNotNull") != null){
                BasicDBList queryList = new BasicDBList();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.put("openid", new BasicDBObject("$exists", true));
                queryList.add(dbObject);
                queryList.add(new BasicDBObject("openid", new BasicDBObject("$ne","")));
                query.put("$and", queryList);
            }
            if (params.get("idCardNoNotNull") != null){
                BasicDBList queryList = new BasicDBList();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.put("idCardNo", new BasicDBObject("$exists", true));
                queryList.add(dbObject);
                queryList.add(new BasicDBObject("idCardNo", new BasicDBObject("$ne","")));
                query.put("$and", queryList);
            }
            if (params.get("idCardUpPicNotNull") != null){
                BasicDBList queryList = new BasicDBList();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.put("idCardUpPic", new BasicDBObject("$exists", true));
                queryList.add(dbObject);
                queryList.add(new BasicDBObject("idCardUpPic", new BasicDBObject("$ne","")));
                query.put("$and", queryList);
            }
            if (params.get("idCardDownPicNotNull") != null){
                BasicDBList queryList = new BasicDBList();
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.put("idCardDownPic", new BasicDBObject("$exists", true));
                queryList.add(dbObject);
                queryList.add(new BasicDBObject("idCardDownPic", new BasicDBObject("$ne","")));
                query.put("$and", queryList);
            }
            if (params.get("realName") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("realName") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("realName", pattern);
            }
            if (params.get("identityAuditStatus") != null) {
                query.put("identityAuditStatus", ObjectUtils.toInteger(params.get("identityAuditStatus")));
            }
		}
        return query;
    }

    /**
     * 设置用户信息中的特殊值
     * @param user
     */
    private void setValueToUser(User user) {
        user.setCreateTimeStr(user.getCreateTime() != null ?
                DateUtils.long2YMDHMS(user.getCreateTime()) : "");
        user.setLastLoginTimeStr(user.getLastLoginTime() != null ?
                DateUtils.long2YMDHMS(user.getLastLoginTime()) : "");
        //2016.5.25日修改，如果限制时间为0的话就把显示时间改成当前时间
        user.setIsAllowCommentEndDateStr("");
        user.setIsAllowCommentEndDateStr(user.getIsAllowCommentEndDate() != 0 ?
                DateUtils.long2YMDHMS(user.getIsAllowCommentEndDate()) : DateUtils.long2YMDHMS(System.currentTimeMillis()));
        user.setIsAllowLiveEndDateStr("");
        user.setIsAllowLiveEndDateStr(user.getIsAllowLiveEndDate() != 0 ?
                DateUtils.long2YMDHMS(user.getIsAllowLiveEndDate()) : DateUtils.long2YMDHMS(System.currentTimeMillis()));
    }

    public void updateDataAfterClose(Long id,Long programId ,long incrBrodCastNum, String... videoId){
        DBObject query = new BasicDBObject();
        query.put("_id", id);
        DBObject incObj = new BasicDBObject();
        incObj.put("watchNum", jedisDAO.getJedisReadTemplate().hlen(Constants.LIVE_ONLINE_TOTALUSER_KEY + programId));
        Long baseLikeNum = ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().hget(CacheConstants.PROGRAM_BASE_LIKENUM, ObjectUtils.toString(programId)), 0L);
        Long likeNum = ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().get(Constants.LIVE_ONLINE_LIKE_KEY + programId), 0L);
        incObj.put("likeNum", baseLikeNum + likeNum);
        incObj.put("commentNum", ObjectUtils.toLong(jedisDAO.getJedisReadTemplate().get(Constants.LIVE_ONLINE_COMMENT_KEY + programId), 0L));
        incObj.put("broadCastNum", incrBrodCastNum);
        this.update(query, new BasicDBObject("$inc", incObj));

        if(null != videoId && videoId.length >0 && StringUtils.isNotBlank(videoId[0])){
            this.update(query,new BasicDBObject("videoId",videoId[0]));
        }
    }

    /**
     * 根据用户标签查询用户列表
     *
     * @param params 模糊查询的查询条件
     * @param orders 排序的条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<User> getUserListByTag(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<User> userList = Lists.newArrayList();
        if (limit == null) {

            limit = DEFAULT_NUM;
        }

        try {

            List<DBObject> pipeline = Lists.newArrayList();

            // 检索条件
            BasicDBObject matchDBObj = new BasicDBObject();
            BasicDBObject matchCondition = new BasicDBObject();

            // 标签
            if (params.get("tagId") != null) {

                matchCondition.put("tags.tagId", ObjectUtils.toLong(params.get("tagId")));
            }
            // 用户状态
            if (params.get("userStatus") != null) {

                matchCondition.put("userStatus", ObjectUtils.toInteger(params.get("userStatus")));
            }

            matchDBObj.put("$match", matchCondition);
            pipeline.add(matchDBObj);

            // 展开条件
            BasicDBObject unwindDBObj = new BasicDBObject();
            unwindDBObj.put("$unwind", "$tags");
            pipeline.add(unwindDBObj);

            // 筛选条件
            BasicDBObject secondMatchDBObj = new BasicDBObject();
            BasicDBObject secondMatchCondition = new BasicDBObject();
            if (params.get("tagId") != null) {

                secondMatchCondition.put("tags.tagId", ObjectUtils.toLong(params.get("tagId")));
            }
            secondMatchDBObj.put("$match", secondMatchCondition);
            pipeline.add(secondMatchDBObj);

            // 排序
            BasicDBObject sortDBObj = new BasicDBObject();
            BasicDBObject sortCondition = new BasicDBObject();
            // 优先级
            sortCondition.put("tags.score", -1);
            // 点赞数
            if (orders.get("likeNum") != null) {

                sortCondition.put("likeNum", ObjectUtils.toInteger(orders.get("likeNum")));
            }
            // 创建时间
            sortCondition.put("createTime", -1);
            sortDBObj.put("$sort", sortCondition);
            pipeline.add(sortDBObj);

            // 分页条件
            BasicDBObject skipDBObj = new BasicDBObject();
            skipDBObj.put("$skip", start);
            pipeline.add(skipDBObj);
            BasicDBObject limitDBObj = new BasicDBObject();
            limitDBObj.put("$limit", limit);
            pipeline.add(limitDBObj);
            AggregationOutput output = this.dbCollection.aggregate(pipeline);
            Iterator<DBObject> result = output.results().iterator();

            while (result.hasNext()) {

                DBObject dbObject = result.next();
                User user = UserConvert.castDBObjectToUser(dbObject);
                userList.add(user);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return userList;
    }

    public List<DBObject> getDefaultPicUsers(String defaultPicture, long startCreateTime)
    {
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo

        Pattern pattern = Pattern.compile("^.*" +defaultPicture + ".*$", Pattern.CASE_INSENSITIVE);
        query.put("picture", pattern);
        query.put("createTime", new BasicDBObject("$gt", startCreateTime));

        List result = Lists.newArrayList();
        DBCursor cur = null;
        try {
            cur = this.getDbCollection().find(query);
            while (cur.hasNext()) {
                result.add(cur.next());
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(cur != null){
                cur.close();
            }
        }
        return result;
    }

    /**
     * 根据用户ID列表获取用户列表
     * @param ids
     * @return
     */
    public List<User> getUserListByIds(String ids, String... readPreference) {

        List<User> result = Lists.newArrayList();

        try {

            BasicDBList values = new BasicDBList();
            String[] idList = ids.split(",");
            for (String id : idList) {
                values.add(ObjectUtils.toLong(id));
            }

            BasicDBObject queryCondition = new BasicDBObject();
            queryCondition.put("_id", new BasicDBObject("$in", values));
            DBCursor cur = null;

            if (readPreference != null && readPreference.length > 0
                    && Constants.MONGO_READPREFERENCE_PRIMARY.equals(readPreference[0])) {

                cur = this.dbCollectionOnPrimary.find(queryCondition);
            } else {

                cur = this.dbCollection.find(queryCondition);
            }

            while (cur.hasNext()) {

                DBObject dbObject = cur.next();
                User user = UserConvert.castDBObjectToUser(dbObject);
                result.add(user);
            }
        } catch (Exception e) {

            logger.error("getUserListByIds error ids===" + ids, e);
        }
        return result;
    }

    /**
     * 根据查询条件获取用户ID列表
     * @param params 查询条件
     * @param orders 排序条件
     * @return
     */
    public List<Long> getUserIdsByParams(Map<String, Object> params, Map<String, Object> orders, String... readPreference) {

        List<Long> result = Lists.newArrayList();

        try {

            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = null;

            if (readPreference != null && readPreference.length > 0
                    && Constants.MONGO_READPREFERENCE_PRIMARY.equals(readPreference[0])) {

                cur = this.dbCollectionOnPrimary.find(query).sort(order);
            } else {

                cur = this.dbCollection.find(query).sort(order);
            }

            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                result.add(ObjUtils.toLong(dbObject.get("_id")));
            }
        } catch (Exception e) {

            logger.error("getUserIdsByParams error", e);
        }

        return result;
    }

    /**
     * 用户相关信息自增或自减
     * @param userId 用户ID
     * @param columnName 列名
     * @param interval 增减幅度
     * @return 增减后的值
     */
    public Long modifyUserInfoByInterval(Long userId, String columnName, Long interval) {

        // 增减后的值
        Long value = 0L;

        BasicDBObject query = new BasicDBObject();
        query.put("_id", userId);

        // 当做自减操作时，要追加当前值>0的限制条件，避免出现负值
        if (interval < 0) {

            query.put(columnName, new BasicDBObject("$gt", 0L));
        }

        DBObject dbObj = this.dbCollection.findAndModify(query, new BasicDBObject("$inc",
                new BasicDBObject(columnName, interval)));

        if (dbObj != null) {

            value = ObjectUtils.toLong(dbObj.get(columnName));
        }

        return value;
    }

    /**
     * 查询昵称重复的用户ID列表
     *
     * @return
     */
    public List<String> getRepeatedNickNameList() {

        List<String> nickNameList = Lists.newArrayList();
        try {

            List<DBObject> pipeline = Lists.newArrayList();

            // 分组条件
            BasicDBObject groupDBObj = new BasicDBObject();
            BasicDBObject groupCondition = new BasicDBObject();
            groupCondition.put("_id", "$nickName");
            groupCondition.put("count", new BasicDBObject("$sum", 1));

            groupDBObj.put("$group", groupCondition);
            pipeline.add(groupDBObj);

            // 映射字段
            BasicDBObject projectDBObj = new BasicDBObject();
            BasicDBObject projectCondition = new BasicDBObject();
            projectCondition.put("nickName", "$_id");
            projectCondition.put("count", 1);
            projectCondition.put("_id", 0);
            projectDBObj.put("$project", projectCondition);
            pipeline.add(projectDBObj);

            // 查询条件
            BasicDBObject matchDBObj = new BasicDBObject();
            BasicDBObject matchCondition = new BasicDBObject();
            matchCondition.put("count", new BasicDBObject("$gt", 1));
            matchDBObj.put("$match", matchCondition);
            pipeline.add(matchDBObj);

            // 排序
            BasicDBObject sortDBObj = new BasicDBObject();
            BasicDBObject sortCondition = new BasicDBObject();
            sortCondition.put("count", -1);
            sortCondition.put("nickName", 1);
            sortDBObj.put("$sort", sortCondition);
            pipeline.add(sortDBObj);

            AggregationOutput output = this.dbCollection.aggregate(pipeline);
            Iterator<DBObject> result = output.results().iterator();

            while (result.hasNext()) {

                DBObject dbObject = result.next();
                String nickName = ObjectUtils.toString(dbObject.get("nickName"));
                System.out.println(nickName);
                nickNameList.add(nickName);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return nickNameList;
    }
}

